package com.zhny.project.txt.indexset.service.impl;

import com.zhny.common.utils.DateUtils;
import com.zhny.common.utils.security.ShiroUtils;
import com.zhny.common.utils.text.Convert;
import com.zhny.project.system.config.service.IConfigService;
import com.zhny.project.txt.dataset.domain.TxtDataset;
import com.zhny.project.txt.dataset.mapper.TxtDatasetMapper;
import com.zhny.project.txt.history.domain.TxtHistory;
import com.zhny.project.txt.history.mapper.TxtHistoryMapper;
import com.zhny.project.txt.indexset.domain.TxtIndexset;
import com.zhny.project.txt.indexset.mapper.TxtIndexsetMapper;
import com.zhny.project.txt.indexset.service.ITxtIndexsetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * TXT指标集Service业务层处理
 *
 * @author yanqun
 * @date 2019-12-10
 */
@Service
public class TxtIndexsetServiceImpl implements ITxtIndexsetService
{
    @Autowired
    private TxtIndexsetMapper txtIndexsetMapper;
    @Autowired
    private TxtDatasetMapper txtDatasetMapper;
    @Autowired
    private TxtHistoryMapper txtHistoryMapper;
    @Autowired
    private IConfigService configService;

    /**
     * 查询TXT指标集
     *
     * @param indexsetKey TXT指标集ID
     * @return TXT指标集
     */
    @Override
    public TxtIndexset selectTxtIndexsetById(String indexsetKey)
    {
        return txtIndexsetMapper.selectTxtIndexsetById(indexsetKey);
    }

    /**
     * 查询TXT指标集列表
     *
     * @param txtIndexset TXT指标集
     * @return TXT指标集
     */
    @Override
    public List<TxtIndexset> selectTxtIndexsetList(TxtIndexset txtIndexset)
    {
        return txtIndexsetMapper.selectTxtIndexsetList(txtIndexset);
    }

    /**
     * 新增TXT指标集
     *
     * @param txtIndexset TXT指标集
     * @return 结果
     */
    @Override
    public int insertTxtIndexset(TxtIndexset txtIndexset)
    {
        txtIndexset.setIndexsetKey(UUID.randomUUID().toString());
        txtIndexset.setCreateTime(DateUtils.getNowDate());
        return txtIndexsetMapper.insertTxtIndexset(txtIndexset);
    }

    /**
     * 修改TXT指标集
     *
     * @param txtIndexset TXT指标集
     * @return 结果
     */
    @Override
    public int updateTxtIndexset(TxtIndexset txtIndexset)
    {
        txtIndexset.setUpdateTime(DateUtils.getNowDate());
        return txtIndexsetMapper.updateTxtIndexset(txtIndexset);
    }

    /**
     * 删除TXT指标集对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteTxtIndexsetByIds(String ids)
    {
        return txtIndexsetMapper.deleteTxtIndexsetByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除TXT指标集信息
     *
     * @param indexsetKey TXT指标集ID
     * @return 结果
     */
    public int deleteTxtIndexsetById(String indexsetKey)
    {
        return txtIndexsetMapper.deleteTxtIndexsetById(indexsetKey);
    }

    //创建指标集
    @Override
    @Transactional
    public  int insertTxtinto(TxtDataset txtDataset, String  deta, List<String> lis, List<String> surface)
    {
        String   table1 = configService.selectConfigByKey("txt_control_table");
        TxtDataset txtDataset2 = new TxtDataset();
        txtDataset2.setDatasetKey(deta);
        TxtDataset txtDataset1 =  txtDatasetMapper.getSurfaceName(txtDataset2.getDatasetKey());

        StringBuffer str1 = new StringBuffer();
        //新增代码
        if (lis.get(0).contains(" ")){
            str1.append(lis.get(0).replace(" ", ","));
        }

        if (lis.get(0).contains("\t")){
            str1.append(lis.get(0).replace("\t", ","));
        }
        if (lis.get(0).contains(",")){
            str1.append(lis.get(0).replace(",", ","));
        }

        StringBuffer str2 = new StringBuffer();
        for (String s : surface) {
            str2.append(s);
        }
        String[] list1 = str1.toString().split(",");
        int mun1 = list1.length;
        String[] list2 = str2.toString().split(",");
        int mun2 = list1.length;
        TxtIndexset txtIndexset = new TxtIndexset();
        for (int i = 0; i<mun1; i++){
            txtIndexset.setIndexsetKey(UUID.randomUUID().toString());
            txtIndexset.setDatasetKey(deta);
            txtIndexset.setDisposeFlag("0");
            txtIndexset.setDeleteFlag(0);
            txtIndexset.setTableId(txtDataset1.getSurfaceName());
            txtIndexset.setFieldName(list1[i]);
            txtIndexset.setEnglishName(list2[i]);
            txtIndexsetMapper.insertTxtIndexset(txtIndexset);
        }
        return 1;
    }

    public  int csvTxtinto(TxtDataset txtDataset, String deta, List<String> lis, List<String> surface){

        String   table1 = configService.selectConfigByKey("txt_control_table");
        TxtDataset txtDataset2 = new TxtDataset();
        txtDataset2.setDatasetKey(deta);
        TxtDataset txtDataset1 =  txtDatasetMapper.getSurfaceName(txtDataset2.getDatasetKey());
        StringBuffer str1 = new StringBuffer();
        for (int i = 0; i < lis.size(); i++) {
            str1.append(lis.get(i).replace(",", ","));
        }
        StringBuffer str2 = new StringBuffer();
        for (String s : surface) {
            str2.append(s);
        }
        String[] list1 = str1.toString().split(",");
        int mun1 = list1.length;
        String[] list2 = str2.toString().split(",");
        int mun2 = list1.length;
        TxtIndexset txtIndexset = new TxtIndexset();
        for (int i = 0; i<mun1; i++){
            txtIndexset.setIndexsetKey(UUID.randomUUID().toString());
            txtIndexset.setDatasetKey(deta);
            txtIndexset.setDisposeFlag("0");
            txtIndexset.setDeleteFlag(0);
            txtIndexset.setTableId(txtDataset1.getSurfaceName());
            txtIndexset.setFieldName(list1[i]);
            txtIndexset.setEnglishName(list2[i]);
            txtIndexsetMapper.insertTxtIndexset(txtIndexset);
        }
        return 1;
    }




    //范围清洗保存
    public int RangeCleanIndex(TxtIndexset txtIndexset){
        String   table = configService.selectConfigByKey("txt_control_table");
        TxtDataset txtDataset = new TxtDataset();
        txtDataset.setDatasetKey(txtIndexset.getDatasetKey());
        //查id
        TxtDataset txtDataset1 =  txtDatasetMapper.seleid(txtDataset.getDatasetKey());
        //查英文名
        TxtIndexset txtIndexset1 =  txtIndexsetMapper.seleEnglishName(txtIndexset.getIndexsetKey());
        System.out.print(txtDataset1.getDatasetId());
        StringBuffer sql = new StringBuffer();
        sql.append("UPDATE " + table +"" + txtDataset1.getDatasetId() + " SET delete_flag=1  WHERE dataset_key = '");
        sql.append(txtIndexset.getDatasetKey() + "' AND (");
        sql.append(txtIndexset1.getEnglishName() + " < '");
        sql.append(txtIndexset.getStartValue() + "'OR ");
        sql.append(txtIndexset1.getEnglishName() + " > '");
        sql.append(txtIndexset.getEndValue() + "')");
        System.out.print(sql);
        List<LinkedHashMap<String, Object>> datatowdpList = txtIndexsetMapper.deleteTxtIndexset(sql.toString());

        //向指标集插入记录
        TxtIndexset txtIndexset3 = new TxtIndexset();
        txtIndexset3.setDisposeFlag("1");
        txtIndexset3.setHandleBy(ShiroUtils.getUserId().toString());
        txtIndexset3.setStartValue(txtIndexset.getStartValue());
        txtIndexset3.setEndValue(txtIndexset.getEndValue());
        txtIndexset3.setIndexsetKey(txtIndexset.getIndexsetKey());
        txtIndexsetMapper.updateTxtIndexset(txtIndexset3);

        //向数据集集插入记录
        TxtDataset txtDataset2 = new TxtDataset();
        txtDataset2.setDisposeIcon("5");
        txtDataset2.setDatasetKey(txtIndexset.getDatasetKey());
        txtDatasetMapper.updateTxtDataset(txtDataset2);

        //向记录表中添加数据
        TxtHistory txtHistory = new TxtHistory();
        txtHistory.setHistoryKey(UUID.randomUUID().toString());
        txtHistory.setDatasetKey(txtIndexset.getDatasetKey());
        txtHistory.setIndexcollectKey(txtIndexset.getIndexsetKey());
        txtHistory.setDisposeType("2");
        txtHistory.setHistoryBy(ShiroUtils.getUserId().toString());
//        txtHistory.setDisposeTime(DateUtils.getNowDate());
        txtHistoryMapper.insertTxtHistory(txtHistory);
        return 1;
    }

    //盒图清洗保存
    public int BoxstxtIndexset(TxtIndexset txtIndexset){
        String   table = configService.selectConfigByKey("txt_control_table");
        TxtDataset txtDataset = new TxtDataset();
        txtDataset.setDatasetKey(txtIndexset.getDatasetKey());
        //查id
        TxtDataset txtDataset1 =  txtDatasetMapper.seleid(txtDataset.getDatasetKey());
        //查英文名
        TxtIndexset txtIndexset1 =  txtIndexsetMapper.seleEnglishName(txtIndexset.getIndexsetKey());
        System.out.print(txtDataset1.getDatasetId());
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT ");
        sql.append(txtIndexset1.getEnglishName());
        sql.append(" FROM " + table +"" +  txtDataset1.getDatasetId() + "  WHERE dataset_key = '");
        sql.append(txtIndexset.getDatasetKey() + "'");
        sql.append(" ORDER BY " + txtIndexset1.getEnglishName() + " ASC LIMIT ");
        sql.append(txtIndexset.getQuanTity());
        List<LinkedHashMap<String, Object>> dpHandles = txtIndexsetMapper.rowcountsort(sql.toString());
        ArrayList<Float> list = new ArrayList<Float>();
        for (LinkedHashMap linkedHashMap : dpHandles) {
            list.add(Float.valueOf(linkedHashMap.get(txtIndexset1.getEnglishName()).toString()));
        }
        Collections.sort(list);
        int Mun = list.size();
        Double Upperposition = Double.valueOf(Mun * 0.75);
        Double all = Math.rint(Upperposition);
        int teger1 = Integer.valueOf(all.intValue());
        Double Lowerposition = Double.valueOf(Mun * 0.25);
        Double add = Math.rint(Lowerposition);
        int teger2 = Integer.valueOf(add.intValue());
        Float value1 = list.get(teger1);
        Float value2 = list.get(teger2);
        StringBuffer sqlz = new StringBuffer();
        sqlz.append("UPDATE " + table + "" + txtDataset1.getDatasetId() + " SET delete_flag= 1  WHERE dataset_key = '");
        sqlz.append(txtIndexset.getDatasetKey() + "'");
        sqlz.append(" AND (" + txtIndexset1.getEnglishName());
        sqlz.append(" < " + value2);
        sqlz.append(" OR " + txtIndexset1.getEnglishName());
        sqlz.append(" > " + value1 + ")");
        txtIndexsetMapper.selectsetsql(sqlz.toString());

        //向指标集插入记录
        TxtIndexset txtIndexset2 = new TxtIndexset();
        txtIndexset2.setDisposeFlag("2");
        txtIndexset2.setHandleBy(ShiroUtils.getUserId().toString());
        txtIndexset2.setIndexsetKey(txtIndexset.getIndexsetKey());
        txtIndexsetMapper.updateTxtIndexset(txtIndexset2);

        //向数据集集插入记录
        TxtDataset txtDataset2 = new TxtDataset();
        txtDataset2.setDisposeIcon("3");
        txtDataset2.setDatasetKey(txtIndexset.getDatasetKey());
        txtDatasetMapper.updateTxtDataset(txtDataset2);

        //向记录表中添加数据
        TxtHistory txtHistory = new TxtHistory();
        txtHistory.setHistoryKey(UUID.randomUUID().toString());
        txtHistory.setDatasetKey(txtIndexset.getDatasetKey());
        txtHistory.setIndexcollectKey(txtIndexset.getIndexsetKey());
        txtHistory.setDisposeType("3");
        txtHistory.setHistoryBy(ShiroUtils.getUserId().toString());
//        txtHistory.setDisposeTime(DateUtils.getNowDate());
        txtHistoryMapper.insertTxtHistory(txtHistory);

        return 1;


    }
    //清除痕迹
    @Transactional
    public int deletedatasetKey(String datasetKey){
        String   table = configService.selectConfigByKey("txt_control_table");
        StringBuffer sql = new StringBuffer();
        TxtDataset txtDataset1 =  txtDatasetMapper.seleid(datasetKey);
//        delete from deal_towdp where dataset_key = #{datasetKey} and delete_flag = 1
        sql.append("delete from " + table + "");
        sql.append(txtDataset1.getDatasetId());
        sql.append(" where dataset_key = '" + datasetKey + "' and delete_flag = 1 ");
        System.out.print(sql);
       int  dele =  txtIndexsetMapper.dewledatamapper(sql.toString());
        return dele;
    }

    public  List<TxtIndexset> selectStoreById(String datasetKey){

        return txtIndexsetMapper.selectStoreById(datasetKey);
    }

    @Transactional
    public List<LinkedHashMap<String, Object>> ListMapStringObject(String filed1, String quality1,String datasetKey){
        int txtDataset = txtDatasetMapper.seletxtDataset(datasetKey);
        TxtDataset txtDataset1 = txtDatasetMapper.getSurfaceName(datasetKey);
            System.out.print(datasetKey);
            StringBuffer sql = new StringBuffer();
            sql.append("SELECT  ");
            if (txtDataset>0){
                sql.append("eigan_value,");
            }
        if (filed1.equals("null") || quality1.equals("null")){
            if (!filed1.equals("null")){
                String filed2 = filed1.substring(4);
                sql.append(filed2);
            }
            if (!quality1.equals("null")){
                String quality2 = quality1.substring(4);
                String[] list = quality2.split(",");
                int mun = list.length;
                List<String> stringB = Arrays.asList(list);
                StringBuffer Sar = new StringBuffer();
                for (int j=0; j<mun; j++){
//                    IFNULL(create_by,0)
                    Sar.append("IFNULL(" + stringB.get(j) + ",0)" );
                    Sar.append(" AS " + stringB.get(j) +",");
                }
                String Sarquality = Sar.substring(0,Sar.length() - 1);
                sql.append(Sarquality);
            }
        }else {
            String filed2 = filed1.substring(4);
            sql.append(filed2 + ",");
            String quality2 = quality1.substring(4);

            String[] list = quality2.split(",");
            int mun = list.length;
            List<String> stringB = Arrays.asList(list);
            StringBuffer Sar = new StringBuffer();
            for (int j=0; j<mun; j++){
//                    IFNULL(create_by,0)
                Sar.append("IFNULL(" + stringB.get(j) + ",0)" );
                Sar.append(" AS " + stringB.get(j) +",");
            }
            String Sarquality = Sar.substring(0,Sar.length() - 1);
            sql.append(Sarquality);
        }
        sql.append(" FROM " + txtDataset1.getSurfaceName());
        sql.append(" WHERE dataset_key =  '");
        sql.append(datasetKey + "'");
        System.out.print(sql);
            List<LinkedHashMap<String, Object>> dpHandles = txtIndexsetMapper.rowcountsort(sql.toString());
       return dpHandles;
    }

    @Override
    public Integer searchEstimate(String indexsetKey) {

        return txtIndexsetMapper.searchEstimate(indexsetKey);
    }
}
